package cn.hp.beauty.service.impl;

import cn.hp.beauty.domain.Menu;
import cn.hp.beauty.domain.Role;
import cn.hp.beauty.domain.Userinfo;
import cn.hp.beauty.mapper.MenuMapper;
import cn.hp.beauty.mapper.RoleMapper;
import cn.hp.beauty.mapper.UserinfoMapper;
import cn.hp.beauty.service.UserinfoService;
import cn.hp.beauty.util.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserinfoServiceImpl implements UserinfoService {

    @Resource
    private UserinfoMapper userinfoMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private MenuMapper menuMapper;

    @Override
    public List<Userinfo> findList(Userinfo userinfo) {
        return userinfoMapper.selectList(userinfo);
    }

    @Override
    public Userinfo findUserByUsername(String username) {
        return userinfoMapper.selectByUsername(username);
    }

    @Override
    public int insertUserinfo(Userinfo userinfo) {
        return userinfoMapper.insertSelective(userinfo);
    }

    @Override
    public int updateUserinfo(Userinfo userinfo) {
        return userinfoMapper.updateByPrimaryKeySelective(userinfo);
    }

    @Override
    public int deleteById(int id) {
        return userinfoMapper.deleteByPrimaryKey(id);
    }

    @Override
    public String getUserAuthority(int uid) {
        StringBuffer authority = new StringBuffer();

        // 第一步：查询用户的角色  Role_
        List<Role> roleList = roleMapper.selectByUID(Long.valueOf(uid));
        if (roleList.size() > 0) {
            String roleCodeStrs = roleList.stream().map(r->"Role_"+r.getRCode()).collect(Collectors.joining(","));
            authority.append(roleCodeStrs);
        }

        // 第二步：遍历用户的角色，根据角色找到资源，并去重
        Set<String> menuCodeSet = new HashSet<>();
        for (Role role : roleList) {
            List<Menu> menuList = menuMapper.selectByRId(Long.valueOf(role.getRId()));
            for (Menu menu : menuList) {
                String perms = menu.getMPerms();
                if (StringUtils.isNotEmpty(perms)) {
                    menuCodeSet.add(perms);
                }
            }
        }

        if (menuCodeSet.size() > 0) {
            authority.append(",");
            String menuCodeStrs = menuCodeSet.stream().collect(Collectors.joining(","));
            authority.append(menuCodeStrs);
        }

        System.out.println(authority.toString());

        return authority.toString();
    }
}